package com.designmodel.designmodel.Factory_Pattern_工厂模式;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

public class BeanFactory {
	static Map<String,Object> container=new HashMap<>();

	static {
		try {
			initFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public  static void  initFactory() throws Exception {
		SAXBuilder saxBuilder=new SAXBuilder();
		Document document=saxBuilder.build(BeanFactory.class.getClassLoader().getResourceAsStream("services.xml"));
		Element element=document.getRootElement();
		List<Element> list=element.getChildren();
		IntStream.range(0,list.size()).forEach(i->{
			Element elementChild = list.get(i);	//attribute为节点属性
			try {

				String id=elementChild.getAttributeValue("id");
				String clazz=elementChild.getAttributeValue("class");

				Class<?> c =Class.forName(clazz);
				Object o=c.newInstance();
				List<Element> propElment=elementChild.getChildren();
				Field[] fields = c.getDeclaredFields();
				for(Field field:fields){
					IntStream.range(0,propElment.size()).forEach(j->{
						String propName=propElment.get(j).getAttributeValue("name");
						String propValue=propElment.get(j).getAttributeValue("value");
						System.out.println(propName+"---"+propValue);
						if(field.getName().equals(propName)){
							String setMethod="set"+String.valueOf(propName.charAt(0)).toUpperCase()+propName.substring(1);
							try {
								Method m=c.getDeclaredMethod(setMethod,field.getType());
								try {
									m.invoke(o,new Object[]{propValue});
								} catch (IllegalAccessException e) {
									e.printStackTrace();
								} catch (InvocationTargetException e) {
									e.printStackTrace();
								}

							} catch (NoSuchMethodException e) {
								e.printStackTrace();
							}
						}

					});

				}


				container.put(id,o);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});


	}

	public    Object getBean(String id){
		return container.get(id);
	}
}
